package com.atguigu.flink.chapter10;

import com.atguigu.flink.bean.OrderEvent;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternFlatSelectFunction;
import org.apache.flink.cep.PatternFlatTimeoutFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.nfa.aftermatch.AfterMatchSkipStrategy;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.List;
import java.util.Map;

/**
 * @Author lzc
 * @Date 2022/7/7 9:05
 */
public class Flink06_High_Project_Order {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        KeyedStream<OrderEvent, Long> stream = env
            .readTextFile("input/OrderLog.csv")
            .map(line -> {
                String[] data = line.split(",");
                return new OrderEvent(
                    Long.valueOf(data[0]),
                    data[1],
                    data[2],
                    Long.parseLong(data[3]) * 1000
                );
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<OrderEvent>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((order, ts) -> order.getEventTime())
            )
            .keyBy(OrderEvent::getOrderId);
        
        
        Pattern<OrderEvent, OrderEvent> pattern = Pattern
            .<OrderEvent>begin("create", AfterMatchSkipStrategy.skipPastLastEvent())
            .where(new SimpleCondition<OrderEvent>() {
                @Override
                public boolean filter(OrderEvent value) throws Exception {
                    return "create".equals(value.getEventType());
                }
            }).optional()
            .next("pay")
            .where(new SimpleCondition<OrderEvent>() {
                @Override
                public boolean filter(OrderEvent value) throws Exception {
                    return "pay".equals(value.getEventType());
                }
            })
            .within(Time.minutes(30));
        
        
        PatternStream<OrderEvent> ps = CEP.pattern(stream, pattern);
        
        SingleOutputStreamOperator<OrderEvent> normal = ps.flatSelect(
            new OutputTag<OrderEvent>("late") {},
            new PatternFlatTimeoutFunction<OrderEvent, OrderEvent>() {
                @Override
                public void timeout(Map<String, List<OrderEvent>> pattern,
                                    long timeoutTimestamp,
                                    Collector<OrderEvent> out) throws Exception {
                    out.collect(pattern.get("create").get(0));
                }
            },
            new PatternFlatSelectFunction<OrderEvent, OrderEvent>() {
                @Override
                public void flatSelect(Map<String, List<OrderEvent>> pattern,
                                       Collector<OrderEvent> out) throws Exception {
                    // 正常:  create + pay
                    // pay
                    if (!pattern.containsKey("create")) {
                        out.collect(pattern.get("pay").get(0));
                    }
                }
            }
        );
    
        normal.getSideOutput(new OutputTag<OrderEvent>("late") {}).union(normal);
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
